package com.math.aistudykbr.utils;

import com.alibaba.fastjson.JSON;
import com.math.aistudykbr.pojo.entity.MindMapNode;
import lombok.extern.slf4j.Slf4j;
//import org.apache.batik.transcoder.TranscoderInput;
//import org.apache.batik.transcoder.TranscoderOutput;
//import org.apache.batik.transcoder.image.PNGTranscoder;
import org.xmind.core.*;
//import org.xmind.core.io.ByteArrayStorage;

import java.io.*;
import java.util.List;

@Slf4j
public class XmindGenerate {

    /**
     * 生成XMind文件
     * 将JSON格式的思维导图数据转换为XMind文件
     *
     * @param jsonData JSON格式的思维导图数据
     * @return 生成的XMind文件的URL
     * @throws CoreException XMind核心异常
     * @throws IOException IO异常
     */
    public static String generateXmind(String jsonData) throws Exception {
        // 1. 解析JSON数据
        List<MindMapNode> rootNodes = JSON.parseArray(jsonData, MindMapNode.class);

        // 2. 创建XMind工作簿
        IWorkbookBuilder builder = Core.getWorkbookBuilder();
        IWorkbook workbook = builder.createWorkbook();
        ISheet sheet = workbook.getPrimarySheet();
        ITopic rootTopic = sheet.getRootTopic();
        rootTopic.setTitleText("核心主题"); // 设置根节点名称

        // 3. 递归生成子节点
        for (MindMapNode node : rootNodes) {
            buildSubTopics(workbook, rootTopic, node);
        }

        // 4. 将XMind文件保存到字节数组
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.save(outputStream);
        byte[] xmindContent = outputStream.toByteArray();

        // 5. 使用FileStorageUtil保存文件并获取URL
        String fileName = "mind-map_" + System.currentTimeMillis() + ".xmind";
        String fileUrl = FileStorageUtil.saveFile(fileName, xmindContent);

        log.info("Xmind文件生成成功！URL: {}", fileUrl);

//        String testUrl = "resource-xmind/35ba352d-ddf7-4a1d-a906-afaf328d1000_mind-map_1746527149204.xmind";
//        String xmindPngUrl = generateXmindImage(testUrl);
//        log.info("Xmind图片生成成功！URL: {}", xmindPngUrl);

        return fileUrl;
    }

    /**
     * 构建XMind子主题
     * 递归处理思维导图节点，将其转换为XMind主题
     *
     * @param workbook XMind工作簿
     * @param parentTopic 父主题
     * @param node 思维导图节点
     */
    private static void buildSubTopics(IWorkbook workbook, ITopic parentTopic, MindMapNode node) {
        ITopic currentTopic = workbook.createTopic();
        currentTopic.setTitleText(node.getContentTxt());

        parentTopic.add(currentTopic); // 挂载到父节点

        // 递归处理子节点
        if (node.getSonNode() != null) {
            for (MindMapNode child : node.getSonNode()) {
                buildSubTopics(workbook, currentTopic, child);
            }
        }
    }
}
